<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use app\common\library\ImageCraw;
use AlibabaCloud\SDK\Imageseg\V20191230\Imageseg;
use \Exception;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Imageseg\V20191230\Models\SegmentHeadAdvanceRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use GuzzleHttp\Psr7\Stream;
class Avatar extends Command
{
    protected function configure()
    {
        $this
            ->setName('AvatarCreate')
            ->setDescription('AvatarCreate');
    }

    protected function execute(Input $input, Output $output)
    {
        $imagePhoto = Db::name('broadcastImagePhoto')
        ->alias('p')->join('__BROADCAST__ b','p.broadcast_id = b.id')->where('b.is_avatar',1)
        ->where('p.status',1)->where('p.avatar_id',0)->limit(1000)->field('p.id,p.broadcast_id,p.broadcast_image_id,p.image,p.avatar_id,p.status')->select();
        echo date('Y-m-d H:i:s');
        if(!empty($imagePhoto)){
            foreach ($imagePhoto as $key => $value) {
                $this->avataradd($value);

                echo date('Y-m-d H:i:s');
            }
        }
        echo date('Y-m-d H:i:s');
    }
    protected function avataradd($photo){
        try {
            //code...
        
            $avatarPath = ROOT_PATH.'public'.DS.'avatar'.DS; //头像路径
            if (!is_dir($avatarPath)) {
                mkdir($avatarPath, 0755, true);
            }
            $tempPath = ROOT_PATH.'public'.DS.'uploads'.DS.'tempimage'.DS;//临时图片路径
            if (!is_dir($tempPath)) {
                mkdir($tempPath, 0755, true);
            } //cdnurl
            $config = get_addon_config('alioss');
            $tempimage = file_get_contents($config['cdnurl'].$photo['image'].'?x-oss-process=image/resize,w_1280');
            $imageUrl = $tempPath.basename($photo['image']);
            file_put_contents($imageUrl,$tempimage);
            unset($tempimage);
            $response = $this->aliImageseg($imageUrl);
            if($response['code'] == '200'){
                $avatarPhoto = [];
                foreach ($response['Data']['Elements'] as $key => $value) { //broadcast_id,broadcast_image_id,id
                    /**
                     * ["Height"] => int(157)
                     *["ImageURL"] => string(256) "http://vibktprfx-prod-prod-damo-eas-cn-shanghai.oss-cn-shanghai.aliyuncs.com/seg-common-image/2023-06-05/1fec5fcd-df60-4ec1-a65a-b38d5b94a396/image0.png?Expires=1685979205&OSSAccessKeyId=LTAI4FoLmvQ9urWXgSRpDvh1&Signature=Xg0IlFTQ29uG%2FhCXS1qtP%2BNsKXs%3D"
                    *["Width"] => int(141)
                    *["X"] => int(774)
                    *["Y"] => int(888)
                    */
                    $cropImg = ImageCraw::open($imageUrl);
                    $filename = $photo['broadcast_id'].'_'.$photo['broadcast_image_id'].'_'.$photo['id'].'_'.($key+1);
                    $cropImg->crop($value['Width'],$value['Height'],$value['X'],$value['Y'])->save($avatarPath.$filename.'.jpg');
                    unset($cropImg);
                    $avatarPhoto[] = [
                        'photo_id'=>$photo['id'],
                        'avatar'=> '/avatar/'.$filename.'.jpg',
                        'avatar_id'=>0,
                        'createtime'=>time(),
                        'updatetime'=>time(),
                        'status'=>0,

                    ];
                }
                if(!empty($avatarPhoto)){
                    Db::name('BroadcastImageAvatar')->insertAll($avatarPhoto);
                }
            
            }
            Db::name('broadcastImagePhoto')->where('id',$photo['id'])->update(['avatar_id'=>1]);
        } catch (Exception $exception) {
            $config = get_addon_config('alioss');
            if(strlen(file_get_contents($config['cdnurl'].$photo['image']))>20500000){
                //Db::name('broadcastImagePhoto')->where('id',$photo['id'])->delete();
            }
        }
    }
    
    protected function aliImageseg($image){
        $config = get_addon_config('alioss');
        $aliConfig = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $config['accessKeyId'],
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $config['accessKeySecret']
        ]);
        // 访问的域名
        $aliConfig->endpoint = "imageseg.cn-shanghai.aliyuncs.com";
        $client =  new Imageseg($aliConfig);
        $file = fopen($image, 'rb');
        $stream = new Stream($file);
        $segmentHeadAdvanceRequest = new SegmentHeadAdvanceRequest([
            "imageURLObject" => $stream
        ]);
        $runtime = new RuntimeOptions([]);
        try {
            $resp = $client->segmentHeadAdvance($segmentHeadAdvanceRequest, $runtime);
            # 获取整体结果
            $respon =json_decode(
                Utils::toJSONString($resp->body),true
            );
            $respon['code']='200';
            return $respon;
            
        } catch (Exception $exception) {
            # 获取整体报错信息
            dump(json_decode( Utils::toJSONString($exception),true));
            # 获取单个字段
            $respon['code']='500';
            return $respon;
        }
    }
}